package main

import (
	"fmt"
	"log"
	"zinxp/ziface"
	"zinxp/znet"
)

//ping test自定义路由
type PingRouter struct {
	znet.BaseRouter
}


func (this *PingRouter)Handle(request ziface.IRequest)  {
	log.Println("Call PingRouter Handle")

	//读取客户端的数据，再回写pinghpingping
	fmt.Println("recv from client: msgID= ",request.GetMsgID(),",data = ",string(request.GetData()))
	//回写数据
	err := request.GetConnection().SendMsg(1,[]byte("ping...ping...ping..."))
	if err != nil {
		log.Println("Handle: call back ping ping ping error")
	}
}

// HelloXinxRouter Handle
type HelloZinxRouter struct {
	znet.BaseRouter
}

func (this *HelloZinxRouter) Handle(request ziface.IRequest)  {
	log.Println("Call HelloZinxRouter Handle")
	fmt.Println("recv from client: msgID= ",request.GetMsgID(),",data = ",string(request.GetData()))
	err := request.GetConnection().SendMsg(1,[]byte("Hello Zinx Router 0.6"))
	if err != nil {
		log.Println(err)
	}
}

func DoConnectionBegin(conn ziface.IConnection)  {
	log.Println("Connection Berfore hook ....")

	//设置两个连接属性
	log.Println("Set conn Name,Hoem done!")
	conn.SetProperty("Name","Nuc")
	conn.SetProperty("Home","www.pronhub.com")
	err := conn.SendMsg(2,[]byte("DOConnection BEGIN..."))
	if err != nil {
		log.Println(err)
	}
}

func DoConnectionLost(conn ziface.IConnection)  {

	//查询连接属性
	if name,err := conn.GetProperty("Name");err == nil{
		log.Println("Conn Property Name = ",name)
	}

	if home,err := conn.GetProperty("Home");err == nil {
		log.Println("Conn Property Home = ",home)
	}
	log.Println("DoconnectionLost is called")
}

func main()  {
	log.SetFlags(log.Lshortfile | log.LstdFlags)
	s := znet.NewServer("[zinx 0.3]")

	s.SetOnConnectStart(DoConnectionBegin)
	s.SetOnConnectStop(DoConnectionLost)

	s.AddRouter(0,&PingRouter{})
	s.AddRouter(1,&HelloZinxRouter{})
	s.Serve()
}